package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.EsServiceI;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.searchbox.client.JestClient;
import io.searchbox.core.DocumentResult;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Component
public class EsServiceImpl implements EsServiceI {
    @Autowired
    private JestClient jestClient;


    private String index_dkshop = "dkshop";
    private String type_tbItem = "tbitem";

    //审核通过增将加到es中
    @Override
    public void addEs(List<TbItem> items) {
        for (TbItem item : items) {
            String itemJson = "";
            try {
                itemJson = new ObjectMapper().writeValueAsString(item);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            //构建es文档对象
            Index esItem = new Index.Builder(itemJson)  //将该对象纳入构建范围
                    .index(index_dkshop) //操作的索引(index==>库)
                    .type(type_tbItem) //操作的类型(type==>表)
                    .id(String.valueOf(item.getId()))  //文档对象的ID
                    .build();
            try {
                DocumentResult result = jestClient.execute(esItem);
                boolean succeeded = result.isSucceeded();
                System.out.println("是否成功："+succeeded);

                jestClient.execute(esItem);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<TbItem> findSearchInfo(String searchInfo,Integer pageNum) {

        //1.构建查询条件
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", searchInfo);

        //2.构建查询语句综合器,负责整合我们的条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(matchQuery);

        //高亮
        HighlightBuilder highlight = new HighlightBuilder();
        highlight.field("sellPoint");
        highlight.field("title");
        highlight.preTags("<span style='color:red'>").postTags("</span>");  //高亮的样式
        sourceBuilder.query(matchQuery);
        sourceBuilder.highlighter(highlight);

        //分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(10);

        //3.综合器输出查询语句字符串
        String queryStr = sourceBuilder.toString();
        System.out.println("综合器综合后的查询语句:=======>" + queryStr);

        //4.构建查询对象
        Search search = new Search.Builder(queryStr)
                .addIndex(index_dkshop) //操作的索引(index==>库)
                .addType(type_tbItem) //操作的类型(type==>表)
                .build();

        //5.查询并返回结果
        SearchResult result = null;
        try {
            result = jestClient.execute(search);
        } catch (IOException e) {
            e.printStackTrace();
        }


        //6.处理结果集
        List<SearchResult.Hit<TbItem, Void>> hitList = result.getHits(TbItem.class);
        List<TbItem> list = new ArrayList<>();
        for (SearchResult.Hit<TbItem, Void> hit : hitList) {
            TbItem item = hit.source;
            Map<String, List<String>> highlightMap = hit.highlight;

            if (highlightMap != null && !highlightMap.isEmpty()) {
                List<String> titleList = highlightMap.get("title");
                if (titleList != null && !titleList.isEmpty()) {
                    item.setTitle(titleList.get(0));
                }
            }
            list.add(item);
        }
        return list;
    }
}
